<template>
  <div>
    <van-cell @click="onClickItem(item)" v-for="(item,index) in suggestions" :key="index" :title="item" icon="search">
      <template #title>
        <div v-html="formatStr(item)"></div>
      </template>
    </van-cell>
    <!-- 搜索提示 -->
    <van-empty v-if="!suggestions.length" image="search" description="暂无建议" />
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import { Toast } from 'vant'
export default {
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  watch: {
    searchText: {
      immediate: true,
      handler (newVal) {
        this.timeout && clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          this.loadSearchSuggestion(newVal)
        }, 600)
      }
    }
  },

  created () {

  },
  beforeDestroy () {
    clearTimeout(this.timeout)
  },
  methods: {
    async loadSearchSuggestion (Val) {
      try {
        const { options: res } = await getSearchSuggestion(Val)
        this.suggestions = res
      } catch (error) {
        Toast('获取建议失败')
      }
    },
    formatStr (str) {
      const Reg = new RegExp(this.searchText, 'gi')
      return str.replace(Reg, `<span style="color:#e00;">${this.searchText}</span>`)
    },
    onClickItem (val) {
      this.$emit('clickitem', val)
    }
  }
}
</script>

<style scoped>

</style>
